<template>
  <el-card shadow="never" class="table-container overflow-hidden">
    <template #header>
      <!-- 表格左上方工具栏 -->
      <template v-for="item in contentConfig.toolbar" :key="item">

        <template v-if="typeof item === 'string'">
          <!-- 刷新 -->
          <template v-if="item === 'refresh'">
            <el-button :icon="Refresh" @click="handleToolbar(item)" />
          </template>
          <!-- 新增 -->
          <template v-else-if="item === 'add'">
            <el-button v-hasPerm="[`${contentConfig.pageName}:${item}`]" type="success" icon="plus"
              @click="handleToolbar(item)">
              {{$t('btn.3')}}
            </el-button>
          </template>
          
          <!-- 批量修改密码 -->
          <template v-else-if="item === 'batchPassword'">
            <el-button type="success" icon="plus"
              @click="handleToolbar(item)">
              {{$t('btn.15')}}
            </el-button>
          </template>
          <!-- 批量修改支付密码 -->
          <template v-else-if="item === 'batchPayPassword'">
            <el-button type="success" icon="plus"
              @click="handleToolbar(item)">
              {{$t('btn.16')}}
            </el-button>
          </template>
          <!-- 删除 -->
          <template v-else-if="item === 'delete'">
            <el-button v-hasPerm="[`${contentConfig.pageName}:${item}`]" type="danger" icon="delete"
              :disabled="removeIds.length === 0" @click="handleToolbar(item)">
              {{$t('btn.4')}}
            </el-button>
          </template>
          <!-- 导出 -->
          <template v-else-if="item === 'export'">
            <!-- v-hasPerm="[`${contentConfig.pageName}:${item}`]" -->
            <el-button type="primary" icon="download" @click="handleToolbar(item)">
              {{$t('btn.5')}}
            </el-button>
          </template>
        </template>
        <!-- 其他 -->
        <template v-else-if="typeof item === 'object'">
          <template v-if="item.auth">
            <el-button :icon="item.icon" :type="item.type || 'default'"
              @click="handleToolbar(item.name)">
              {{ item.text }}
            </el-button>
          </template>
          <template v-else>
            <el-button :icon="item.icon" type="default" @click="handleToolbar(item.name)">
              {{ item.text }}
            </el-button>
          </template>
        </template>
      </template>
    </template>
    <!-- 列表 -->
    <el-table  v-loading="loading" v-bind="contentConfig.table" stripe  :data="pageData"
      header-row-class-name="custom-header" 
      @selection-change="handleSelectionChange" @sort-change="sortChange" class="overflow-y-scroll" :height="gridOptions?.height || 'calc(100vh - 280px)'">
      <template v-for="col in contentConfig.cols" :key="col.prop">
        <!-- 列操作栏 -->
        <template v-if="col.templet === 'tool'">
          <!-- :sort-by="sortBy" -->
          <el-table-column v-bind="col" :label="col.label">
            <template #default="scope">
              <slot name="tool" v-bind="scope"></slot>
              <template v-for="item in col.operat" :key="item">
                <template v-if="typeof item === 'string'">
                  <!-- 编辑/删除 -->
                  <template v-if="item === 'edit' || item === 'delete'">
                    <el-button v-hasPerm="[`${contentConfig.pageName}:${item}`]"
                      :type="item === 'edit' ? 'primary' : 'danger'" :icon="item" size="small" link @click="
                        handleOperat({
                          name: item,
                          row: scope.row,
                          column: scope.column,
                          $index: scope.$index,
                        })
                      ">
                      {{$t(item === "edit" ? "oper.1" : "oper.2")}}
                    </el-button>
                  </template>
                </template>
                <!-- 其他 -->
                <template v-else-if="typeof item === 'object'">
                  <template v-if="item.auth">
                    <el-button v-hasPerm="[`${contentConfig.pageName}:${item.auth}`]" :icon="item.icon"
                      :type="item.type ||'primary'" size="small" link @click="
                        handleOperat({
                          name: item.name,
                          row: scope.row,
                          column: scope.column,
                          $index: scope.$index,
                        })
                      ">
                      {{ item.text }}
                    </el-button>
                  </template>
                  <template v-else>
                    <el-button :icon="item.icon" :type="item.type ||'primary'" size="small" link @click="
                        handleOperat({
                          name: item.name,
                          row: scope.row,
                          column: scope.column,
                          $index: scope.$index,
                        })
                      ">
                      {{ item.text }}
                    </el-button>
                  </template>
                </template>
              </template>
            </template>
          </el-table-column>
        </template>
        <!-- 自定义 -->
        <template v-else-if="col.templet === 'custom'">
          <el-table-column v-bind="col" :label="col.label" >
            <template #default="scope">
              <slot :name="col.slotName ?? col.prop" :prop="col.prop" v-bind="scope"></slot>
            </template>
          </el-table-column>
        </template>

        <template v-else-if="col.templet === 'customStor'">
          <slot :name="col.slotName ?? col.prop" :prop="col.prop" v-bind="col"></slot>
          <!-- <el-table-column v-bind="col" :label="col.label">
            <template #default="scope">  </template>
  </el-table-column> -->
        </template>
        <template v-else-if="col.type === 'time'">
          <el-table-column v-bind="col" :label="col.label" >
            <template #default="scope">
              {{scope.row[col.prop] ? moment(scope.row[col.prop]).format('YYYY-MM-DD HH:mm:ss') : '--' }}
            </template>
          </el-table-column>
        </template>
        <template v-else-if="col.type === 'img'">
          <el-table-column v-bind="col" :label="col.label">
            <template #default="scope">
              <el-image class="w-auto h-[40px]" :src="scope.row[col.prop]" :zoom-rate="1.2" :max-scale="7"
                :min-scale="0.2" :preview-src-list="[scope.row[col.prop]]" fit="cover" :z-index="10"
                preview-teleported />
            </template>
          </el-table-column>
        </template>
        <template v-else-if="col.type === 'link'">
          <el-table-column v-bind="col" :label="col.label" >
            <template #default="scope">
              <el-link type="success" @click="linkTo(scope.row[col.prop])">{{$t('oper.6')}}</el-link>
            </template>
          </el-table-column>
        </template>
        <!-- 其他 -->
        <template v-else>
          <el-table-column v-bind="col" :label="col.label" :min-width="col.minWidth || '150px'">
          </el-table-column>
        </template>
      </template>
    </el-table>
    <!-- 分页 -->
    <pagination class="flex flex-row justify-end" v-model:total="total" v-model:page="queryParams.page" v-model:limit="queryParams.per_page"
      @pagination="handlePagination" v-if="total" />
  </el-card>
</template>

<script setup>
import moment from 'moment'
import { ref, reactive, onMounted, nextTick } from "vue";
import Pagination from "@/components/Pagination/index.vue";
import { Refresh } from '@element-plus/icons-vue'
const { t } = useI18n();
const props = defineProps({
  contentConfig: {
    type: Object,
    default: {
      // 页面名称(参与组成权限标识,如sys:user:xxx)
      pageName: '',
      // table组件属性
      table: [],
      // 列表的网络请求函数(需返回promise)
      indexAction: (data) => Promise,
      // 删除的网络请求函数(需返回promise)
      deleteAction: (id) => Promise,
      // 导出的网络请求函数(需返回promise)
      exportAction: (id) => Promise,
      defSearch: true,
      // 主键名(默认为id)
      pk: '',
      // 表格工具栏(默认支持refresh,add,delete,export,也可自定义)["refresh", "add", "delete", "export", { auth: '', icon: '', name: '', text: '' }]
      toolbar: [],
      // table组件列属性(额外的属性templet,operat,slotName)
      cols: []
    }
  },
  gridOptions:{
    type: Object,
    default: ()=> ({})
  }
})
// 定义自定义事件
const emit = defineEmits(["addClick", 'exportClick', 'toolbarClick', 'editClick', 'operClick'])
// 暴露的属性和方法
defineExpose({ fetchPageData, exportPageData });

// 主键
const pk = props.contentConfig.pk ?? "id";
// 加载状态
const loading = ref(false);
// 删除ID集合 用于批量删除
const removeIds = ref([]);
// 选择的数据
const rowSelection = ref([]);
// 数据总数
const total = ref(0);
// 列表数据
const pageData = ref([]);
// 搜索参数
const queryParams = reactive({
  page: 1,
  per_page: 20,
});
// 上一次搜索条件
let lastFormData = {};
// 获取分页数据
function fetchPageData (formData, isRestart = false) {
  console.log('formData====', formData);

  loading.value = true;
  if (formData && Object.keys(formData).length) {
    lastFormData = formData;
  } else {
    formData = lastFormData
  }
  if (isRestart) {
    queryParams.page = 1;
    queryParams.per_page = 20;
  }
  props.contentConfig.indexAction({ ...queryParams, ...formData })
    .then(({ data, meta }) => {
      total.value = meta?.total || data.length;
      pageData.value = data;
    })
    .finally(() => {
      loading.value = false;
    });
}
const sortChange = (e) => {
  console.log(e);

}
const sortFn = (e) => {
  console.log('sortFn', e);

}
// 行选中
function handleSelectionChange (selection) {
  removeIds.value = selection.map((item) => item[pk]);
  rowSelection.value = selection;
}
// 刷新
function handleRefresh () {
  fetchPageData({});
}
// 删除
function handleDelete (id) {
  const ids = [id || removeIds.value].join(",");
  if (!ids) {
    ElMessage.warning(t('hint.148'));
    return;
  }

  ElMessageBox.confirm(t("hint.57"), t("hint.1"), {
    type: "warning",
  }).then(function () {
    if (props.contentConfig.deleteAction) {
      props.contentConfig.deleteAction(ids).then(() => {
        ElMessage.success(t("hint.7"));
        handleRefresh();
      });
    } else {
      ElMessage.error(t('hint.147'));
    }
  });
}
// 分页
function handlePagination () {
  fetchPageData(lastFormData);
}
// 操作栏
function handleToolbar (name) {
  switch (name) {
    case "refresh":
      handleRefresh();
      break;
    case "add":
      emit("addClick");
      break;
    case "delete":
      handleDelete();
      break;
    case "export":
      emit("exportClick");
      break;
    default:
      emit("toolbarClick", name,removeIds.value);
      break;
    case "batchPassword":
      emit("batchPasswordClick",removeIds.value);
      break;
    case "batchPayPassword":
      emit("batchPayPasswordClick",removeIds.value);
      break;
  }
}
// 操作列
function handleOperat (data) {
  switch (data.name) {
    case "edit":
      emit("editClick", data.row);
      break;
    case "delete":
      handleDelete(data.row[pk]);
      break;
    default:
      emit("operatClick", data);
      break;
  }
}
// 导出Excel
function exportPageData (queryParams) {
  if (props.contentConfig.exportAction) {
    props.contentConfig.exportAction(queryParams).then((response) => {
      console.log('response', response);
      ElMessage.success(response.msg);
    });
  } else {
    ElMessage.error("未配置exportAction");
  }
}
const linkTo = (url) => {
  window.open(url)
}
onMounted(() => {
  console.log('ddd===111111', props.contentConfig);

  if (props.contentConfig.defSearch !== false) {
    nextTick(() => {
      fetchPageData();
    })
  }
})
</script>

<style lang="scss" scoped>
:deep(.el-card__footer) {
  padding: 0;
}
:deep(.custom-header) {
  font-weight: 600;
}
</style>
